import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "@/views/Layout";
import ArticleDetail from "@/views/ArticleDetail";
import Article from "@/views/Article.vue";
import Collect from "@/views/Collect.vue";
import Like from "@/views/Like.vue";
import User from "@/views/User.vue";
import Login from "@/views/Login.vue";
import Register from "@/views/Register.vue";
import UserUtil from "@/utils/UserUtil";
import { Toast } from "vant";
Vue.use(VueRouter);

const router = new VueRouter({
  // mode: "history",
  routes: [
    { path: "/", redirect: "/home/article" },
    {
      path: "/home",
      component: Layout,
      children: [
        // { path: "/", redirect: "/article" },
        { path: "article", component: Article },
        { path: "collect", component: Collect },
        { path: "like", component: Like },
        { path: "user", component: User },
      ],
    },
    { path: "/detail/:id", component: ArticleDetail, name: "detail" },
    { path: "/login", component: Login },
    { path: "/register", component: Register },
    { path: "*", redirect: "/home/article" },
  ],
  linkActiveClass: "active",
  linkExactActiveClass: "exact-active",
});

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const authPages = ["/home/user", "/home/collect", "/home/like"];

  if (authPages.includes(to.path)) {
    const user = UserUtil.getUser();
    if (!user) {
      Toast("请先登录");
      // next(false);
      router.replace({
        path: "/login",
        query: { redirect: to.fullPath }, // 保存要跳转的路径
      });
      return;
    }
  }
  next();
});

export default router;
